package utils

import (
	"io"
	"sync"
)

type SyncBuffer struct {
	rw       sync.RWMutex
	buf      BytesBuilder
	readPosi int
}

func (this *SyncBuffer) Write(buf []byte) (int, error) {
	this.rw.Lock()
	defer this.rw.Unlock()
	return this.buf.Write(buf)
}

func (this *SyncBuffer) Len() int {
	this.rw.RLock()
	defer this.rw.RUnlock()
	remain := this.buf.Len() - this.readPosi
	return remain
}

func (this *SyncBuffer) Clean() {
	this.rw.Lock()
	defer this.rw.Unlock()
	this.buf.Reset()
}

func (this *SyncBuffer) Read(buf []byte) (int, error) {
	this.rw.RLock()
	defer this.rw.RUnlock()
	n := len(buf)
	remain := this.buf.Len() - this.readPosi
	if remain == 0 {
		return 0, io.EOF
	}
	if remain < n {
		n = remain
	}
	copy(buf, this.buf.Buff(this.readPosi, n))
	return n, nil
}
